//
//  CZNetworkTool.swift
//  swiftweibo
//
//  Created by Apple on 15/11/25.
//  Copyright © 2015年 tzw. All rights reserved.
//

import UIKit
import AFNetworking
// 网络请求的枚举
enum CZNetworkMethod: String{
    case GET = "GET"
    case POST = "POST"
}
// 统一错误处理
enum CZNetworkToolError: Int{
    case EmptyAccessToken = -1
    case EmptyUid = -2
    // 属性，根据不同的枚举类型返回不同的值 
    var description: String{
        switch self{
        case .EmptyAccessToken:
                return "AccessToken没有值"
        case .EmptyUid:
                return "Uid没有值"
        }
    }
    // 根据当前类型返回一个NSError
    func error()->NSError{
        return NSError(domain: "cn.error.net", code: self.rawValue, userInfo: ["description":self.description])
    }
}



// 网络单例
class CZNetworkTool: AFHTTPSessionManager {

    // 单例
    static let sharedInstance: CZNetworkTool = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tool = CZNetworkTool(baseURL: baseURL)
        // 设置响应的数据
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
        
        }()
    // MARK: - 请求授权
    private let client_id = "789141090"
    // 申请应用时分配的
    private let client_secret = "a9784063434b12d85dacf3df3aab3d5b"
    // 授权返回地址
    let redirect_uri = "http://www.baidu.com/"
    // 返回授权界面的url
    func oauthURL()->NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    // MARK: - 加载网络请求加载AccessToken,只负责加载数据
    func loadAccessToken(code: String,finished:(result: [String: AnyObject]?, error: NSError?)->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 拼接参数
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
            
        ]
        request(requestMethod: CZNetworkMethod.POST, urlString: urlString, parameters: parameters, needAccessToken: false, finished: finished)
//        requestPOST(urlString, parameters: parameters, finished: finished)
        // post发送网络请求
//        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            // 完成回调
////            print("\(result)")
//            finished(result: result as? [String : AnyObject], error: nil)
//            
//            }) { (_, error) -> Void in
//                
//                finished(result: nil, error: error)
//                print("发送请求出错：\(error)")
//        }
    }
    // MARK:获取用户数据
    func loadUserInfo(finished:(result:[String : AnyObject]?,error: NSError?)->()){
        // 获取access_token
        // 判断是否获得利用守卫来判断，守卫和可选绑定正好相反
//        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else{
//        let error = CZNetworkToolError.EmptyAccessToken.error()
//        print("access_token没有值")
//            return
//        }
        guard let uid = CZUserAccount.loadUserAccount()?.uid else{
            print("uid 为空")
            return
        }
    let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = [
//            "access_token": access_token,
//            uid需要查询的用户ID。
            "uid": uid
        ]
        request(requestMethod: CZNetworkMethod.GET, urlString: urlString, parameters: parameters, needAccessToken: true, finished: finished)
//        requestGET(urlString, parmeters: parameters, finished: finished)
//        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("\(result)")
//            finished(result: result as? [String : AnyObject], error: nil)
//            
//            }) { (_ , error) -> Void in
//                finished(result: nil, error: error)
//        }
    }
    // 加载微数据
    func loadStatus(finished:(result:[String : AnyObject]?,error: NSError?)->()){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else{
//            print("获取access_token失败")
//            return
//        }
        let parameters = [String: AnyObject]()
//        requestGET(urlString, parmeters: parameters, finished: finished)
        let debug = false
        if debug{
            loadLocalStatus(finished)
        }else
        {
            request(requestMethod: CZNetworkMethod.GET, urlString: urlString, parameters: parameters, needAccessToken: true, finished: finished)
        }
    }
    // MARK: - 封装
    typealias NetworkCallBack = (result:[String : AnyObject]?,error: NSError?)->()
    //  MARK: - 加载网络数据
    private func loadLocalStatus(finished:NetworkCallBack){
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        // 加载数据
        let data = NSData(contentsOfFile: path)!
        // 将二进制转成JSON格式
        do{
            let json = try?NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
            finished(result: json as? [String: AnyObject], error: nil)
        }catch{
            print("出现异常")
        }
    }
    
    // 封装get请求
    func requestGET(urlString: String,parmeters:[String: AnyObject],finished: NetworkCallBack){
        GET(urlString, parameters: parmeters, success: { (_, result) -> Void in
            finished(result: result as? [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    // 封装post请求
    func requestPOST(urlString: String,parameters: [String : AnyObject],finished:NetworkCallBack){
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            finished(result: result as? [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
    }
    // 封装网络请求的统一入口
    func request(requestMethod requestMethod:CZNetworkMethod,urlString: String,var parameters: [String : AnyObject],needAccessToken: Bool,finished:NetworkCallBack){
        // 判断是否需要拼接AccessToken
        if needAccessToken {
            guard let access_token = CZUserAccount.loadUserAccount()?.access_token else{
                print("access_token没有值")
                return
            }
            // 拼接access_token
            parameters["access_token"] = access_token
//            print("access_token:\(access_token)")
        }
        
        let sucessCallBack = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result as? [String: AnyObject], error: nil)
        }
        
        let failureCallBack =  { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(result: nil, error: error)
        }
        
        // 发送请求
        switch requestMethod{
            case .GET:
            GET(urlString, parameters: parameters, success:sucessCallBack,failure:failureCallBack)
            
        case .POST:
            POST(urlString, parameters: parameters, success: sucessCallBack, failure: failureCallBack)
        }
    }
}
